//
//  SPFilter.swift
//  PerfectTemplatePackageDescription
//
//  Created by John on 2018/6/5.
//

import PerfectHTTP
import PerfectRequestLogger

//请求过滤器
struct Filter1:HTTPRequestFilter {
    func filter(request: HTTPRequest, response: HTTPResponse, callback: (HTTPRequestFilterResult) -> ()) {
        let param = request.param(name:"message")
        if  param != nil && param!.count >= 10{
            callback(.continue(request, response))
        }
        else{
            response.status = .custom(code: 10086, message: "not nil")
            response.appendBody(string: "不能为空")
            callback(.halt(request, response))
        }
    }
}

struct Filter2:HTTPRequestFilter {
    func filter(request: HTTPRequest, response: HTTPResponse, callback: (HTTPRequestFilterResult) -> ()) {
        let param = request.param(name:"detail")
        if  param != nil && param!.count >= 10{
            callback(.continue(request, response))
        }
        else{
            response.status = .custom(code: 10087, message: "at lease 10")
            response.appendBody(string: "不能少于10个字符")
            callback(.halt(request, response))
        }
    }
}

// 初始化日志记录器
let httplogger = RequestLogger()

public func makeRequestFilter() -> [(HTTPRequestFilter,HTTPFilterPriority)]{
    let requestFilters:[(HTTPRequestFilter,HTTPFilterPriority)] = [
        (httplogger, HTTPFilterPriority.high),
        (Filter1(), HTTPFilterPriority.high),
        (Filter2(), HTTPFilterPriority.medium),
    ]
    return requestFilters
}

public func makeResponseFilter() -> [(HTTPResponseFilter,HTTPFilterPriority)]{
    let responseFilters:[(HTTPResponseFilter,HTTPFilterPriority)] = [
        (httplogger, HTTPFilterPriority.low),
        ]
    return responseFilters
}

//404响应过滤器
struct Filter404:HTTPResponseFilter {
    func filterHeaders(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
        if case .notFound = response.status {
            response.setBody(string: "文件\(response.request.path)不存在.")
            response.setHeader(.contentLength, value: "\(response.bodyBytes.count)")
        }
        else{
            callback(.continue)
        }
    }
    
    func filterBody(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
        callback(.continue)
    }
    
}
